const OpenAI = require('openai');

class AIService {
    constructor() {
        // 验证必要的配置
        if (!process.env.QWEN_API_KEY) {
            throw new Error('Qwen API key not configured');
        }

        this.openai = new OpenAI({
            apiKey: process.env.QWEN_API_KEY,
            baseURL: process.env.QWEN_BASE_URL || 'https://dashscope.aliyuncs.com/compatible-mode/v1'
        });

        // 定义不同的 prompts
        this.PROMPTS = {
            englishTeacher: "You are an AI English teaching assistant. Your role is to help users learn English effectively. Please provide explanations in both English and Chinese. Focus on grammar corrections, pronunciation tips, and vocabulary enhancement.",
            wordGame: `You are a vocabulary teacher. Your task is to generate exactly 10 NEW English words with their detailed information based on the given level.
                      Do not repeat any words from the conversation history.
                      For each word, provide the following information in this exact format:
                      1. english_word [part_of_speech] /phonetic/ - chinese_meaning
                      
                      Part of speech abbreviations to use:
                      n. (noun), v. (verb), adj. (adjective), adv. (adverb), prep. (preposition), conj. (conjunction), pron. (pronoun)
                      
                      Example format:
                      1. appreciate [v.] /əˈpriːʃieɪt/ - 欣赏；感激
                      2. magnificent [adj.] /mæɡˈnɪfɪsnt/ - 宏伟的；壮丽的
                      
                      The level will be one of: 小学英语、初中英语、高中英语、大学英语四级、大学英语六级、专业四级、专业八级、雅思、托福.
                      Ensure the words and their difficulty match the specified level.
                      Do not include any other content or explanations.`
        };
    }

    static getInstance() {
        if (!AIService.instance) {
            AIService.instance = new AIService();
        }
        return AIService.instance;
    }

    async getAIResponse(message, sessionMessages = [], onProgress) {
        try {
            console.log('开始调用AI服务...');
            
            // 构建消息历史
            const messages = [
                { 
                    role: "system", 
                    content: "You are an AI English teaching assistant. Your role is to help users learn English effectively. Please provide explanations in both English and Chinese. Focus on reading comprehension and vocabulary enhancement in sentence construction." 
                },
                ...sessionMessages, // 添加历史消息
                { role: "user", content: message } // 添加新消息
            ];

            console.log('发送消息历史:', messages);

            const completion = await this.openai.chat.completions.create({
                model: "qwen-max-latest",
                messages: messages,
                stream: true,
                temperature: 0.7,
                max_tokens: 2000,
            });

            let fullResponse = '';
            
            try {
                for await (const chunk of completion) {
                    console.log('收到AI响应chunk:', chunk);
                    const content = chunk.choices[0]?.delta?.content || '';
                    if (content) {
                        fullResponse += content;
                        if (onProgress) {
                            onProgress(content);
                        }
                    }
                }
            } catch (streamError) {
                console.error('流处理错误:', streamError);
                throw streamError;
            }

            return {
                content: fullResponse,
                role: 'assistant'
            };
        } catch (error) {
            console.error('AI服务错误:', {
                message: error.message,
                response: error.response?.data,
                stack: error.stack
            });
            throw new Error(`AI服务错误: ${error.message}`);
        }
    }

    // 修改单词生成方法，添加会话历史支持
    async getWordsForLevel(level, sessionMessages = []) {
        try {
            console.log('开始生成单词列表...', { level });
            
            const messages = [
                { 
                    role: "system", 
                    content: this.PROMPTS.wordGame
                },
                ...sessionMessages.map(msg => ({
                    role: "assistant",
                    content: msg.content
                })),
                {
                    role: "user",
                    content: `Generate 10 new words for level: ${level}`
                }
            ];

            const completion = await this.openai.chat.completions.create({
                model: "qwen-max-latest",
                messages: messages,
                temperature: 0.7,
                max_tokens: 2000,
            });

            return completion.choices[0].message.content;
        } catch (error) {
            console.error('生成单词错误:', error);
            throw new Error(`单词生成错误: ${error.message}`);
        }
    }
}

module.exports = AIService.getInstance(); 